package pers.youqu.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import pers.youqu.common.dto.PageDTO;
import pers.youqu.common.exception.YqException;
import pers.youqu.item.dto.BrandDTO;
import pers.youqu.item.mapper.BrandMapper;
import pers.youqu.item.po.Brand;
import pers.youqu.item.po.CategoryBrand;
import pers.youqu.item.service.BrandService;
import pers.youqu.item.service.CategoryBrandService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jason
 * @version 1.0.0
 * @date 2020/12/5 14:19
 * @Description TODO
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public BrandDTO findBrandById(Long id) {
        return new BrandDTO(this.getById(id));
    }

    @Override
    public List<BrandDTO> findBrandsByIds(List<Long> ids) {
        return BrandDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public PageDTO<BrandDTO> findBrandsByPage(Integer page, Integer rows, String key) {
        // 1.分页信息的健壮性处理
        page = Math.min(page, 100); // 最大页数100
//        rows = Math.max(rows, 5); // 每页最小条数5
        // 2.分页
        Page<Brand> info = new Page<>(page, rows);
        // 3.判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(info);

        // 5.获取查询数据
        List<Brand> pageData = info.getRecords();
        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(pageData));
    }

    @Override
    public List<BrandDTO> findBrandsByCategoryId(Long id) {

        List<Long> brandIds = categoryBrandService.query().eq("category_id", id).list()
                .stream().map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
//        return BrandDTO.convertEntityList(this.listByIds(brandIds));
        if (CollectionUtils.isEmpty(brandIds)) {
            throw new YqException(204, "分类对应的品牌为空");
        }
        return findBrandsByIds(brandIds);
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean flag = save(brand);
        if (!flag) {
            throw new YqException(500, "新增品牌出错");
        }
        // 保存后获取id
        Long id = brand.getId();

        flag = saveCategoryBrand(brandDTO.getCategoryIds(), id);
        if (!flag) {
            throw new YqException(500, "分类品牌中间表数据插入错误");
        }
    }

    private boolean saveCategoryBrand(List<Long> cIds, Long id) {
        boolean flag;
        List<CategoryBrand> categoryBrands = cIds.stream()
                .map(categoryId -> CategoryBrand.of(categoryId, id)) // 遍历获取分类id通过构造方法构造中间表对象
                .collect(Collectors.toList()); // 获取中间表对象的集合

        // 调用中间表业务方法保存中间表数据
        flag = categoryBrandService.saveBatch(categoryBrands);
        return flag;
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {

        Brand brand = brandDTO.toEntity(Brand.class);
        boolean flag = updateById(brand);
        if (!flag) {
            throw new YqException(500, "更新品牌失败");
        }

        flag = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if (!flag) {
            throw new YqException(500, "删除分类品牌中间表出错");
        }

        flag = saveCategoryBrand(brandDTO.getCategoryIds(), brandDTO.getId());
        if (!flag) {
            throw new YqException(500, "分类品牌中间表数据插入错误");
        }
    }

    @Override
    @Transactional
    public void deleteBrand(Long id) {
        boolean flag = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
        if (!flag) {
            throw new YqException(500, "分类品牌中间表数据删除错误");
        }
        flag = removeById(id);
        if (!flag) {
            throw new YqException(500, "品牌数据删除错误");
        }
    }
}
